#!/bin/sh -e

# Copyright (C) 2018 Ariadne Devos
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.

# Run this script if you have a lot of untracked files in your tree,
# before pushing to the public repo.

set -e
LC_ALL=C.UTF-8
export LC_ALL

type="$1"
func="$2"
source="$3"


IFS=' '
sizes='2 4 8 16 32 64'

cat <<EOF
#include <sHT/vector.h>
EOF
for size in $sizes; do
cat <<EOF
#if defined(sHT_target_${size}) && (${size} >= sHT_${type}_bytes)
# define sHT_size ${size}
# define sHT_target sHT_target_${size}
# define ${func} ${func}_${size}
# include "${source}"
# undef ${func}
# undef sHT_target
# undef sHT_size
#endif
EOF
done

cat <<EOF
/* musl doesn't allow GNU indirect functions.
   Do the portable thing: save a pointer.  */

#if 0
EOF
for size in $sizes; do
cat <<EOF
#elif defined(sHT_target_${size}) && (${size} >= sHT_${type}_bytes)
typedef __typeof__(&${func}_${size}) ${func}_type;
EOF
done
cat <<EOF
#else
# error impossible
#endif

static const ${func}_type ${func}_variants[] = {
EOF
for size in $sizes; do
cat <<EOF
#if defined(sHT_target_${size}) && (${size} >= sHT_${type}_bytes)
	${func}_${size},
#endif
EOF
done
cat <<EOF
};
EOF
